  import CryptoJS from 'crypto-js'

/**
 * CryptoJS 加密
 *
 * @param {String} encryptData  需要加密数据
 * @returns 加密后的数据
 * @memberof Utils
 */
export const encrypt = (encryptData) => {
  var key = CryptoJS.enc.Utf8.parse('as-Crypto-js')
  var srcs = CryptoJS.enc.Utf8.parse(encryptData)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * CryptoJS 解密
 *
 * @param {String} encryptData  需要加密数据
 * @returns 解密后的数据
 * @memberof Utils
 */
export const decrypt = (encryptData) => {
  var key = CryptoJS.enc.Utf8.parse('as-Crypto-js')
  var decrypt = CryptoJS.AES.decrypt(encryptData, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}


// ------------AES-------------
function getAesString(data, key, iv) { //加密
  let keys = CryptoJS.enc.Utf8.parse(key)
  let vis = CryptoJS.enc.Utf8.parse(iv)
  let encrypt = CryptoJS.AES.encrypt(data, keys, {
    iv: vis, //iv偏移量 CBC需加偏移量
    mode: CryptoJS.mode.CBC, //CBC模式
    // mode: CryptoJS.mode.ECB, //ECB模式
    padding: CryptoJS.pad.Pkcs7 //padding处理
  });
  // debugger
  return encrypt.toString(); //加密完成后，转换成字符串
}

function getDAesString(encrypted, key, iv) { // 解密
  var key  = CryptoJS.enc.Utf8.parse(key);
  var iv   = CryptoJS.enc.Utf8.parse(iv);
  var decrypted =CryptoJS.AES.decrypt(encrypted,key,{
    iv:iv,
    mode:CryptoJS.mode.CBC,
    padding:CryptoJS.pad.Pkcs7
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

// AES 对称秘钥加密
const aes = {
  en: (data, key) => getAesString(data, key.key, key.iv),
  de: (data, key) => getDAesString(data, key.key, key.iv)
};
// BASE64
const base64 = {
  en: (data) => CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data)),
  de: (data) => CryptoJS.enc.Base64.parse(data).toString(CryptoJS.enc.Utf8)
};
// SHA256
const sha256 = (data) => {
  return CryptoJS.SHA256(data).toString();
};
// MD5
const md5 = (data) => {
return CryptoJS.MD5(data).toString();
};

export { aes, md5, sha256, base64 };